<?php
namespace App\Services\Exchangerate\Exchangerate;

use App\Models\Exchangerate\Exchangerate;
use Illuminate\Support\Facades\DB;
use App\Services\Manage\ManageIndex;
/**
 * 汇率 逻辑层
 * Class ExchangerateLogic
 * @package App\Services\Exchangerate\Exchangerate
 */
class ExchangerateLogic 
{
    /*添加一条汇率记录表*/
    public function addRate($data): array 
    {
        $data['millisecond'] = get_millisecond();
        $data['update_time'] = $data['create_time'] =time();
        $res = Exchangerate::insertGetId($data);
        return auto_return($res, '添加成功');
    }

    /*修改一条汇率记录*/
    public function updateRate($data): array 
    {
        $_where = [
            ['id', '=', $data['id']],['status','=',1]
        ];
        $rateInfo = Exchangerate::where($_where)->first();
        if(!$rateInfo){
            return verify_err(null, '没有该条记录');
        }
        //对价格进行验证
        $max_price = $data['max_price'] ?? $rateInfo['max_price'];
        $min_price = $data['min_price'] ?? $rateInfo['min_price'];
        $open_price = $data['open_price'] ?? $rateInfo['open_price'];
        $close_price = $data['close_price'] ?? $rateInfo['close_price'];
        $now_price = $data['now_price'] ?? $rateInfo['now_price'];
        if($max_price < $min_price){    return verify_err(null, '最高价不能小于最低价');  }
        if($open_price < $min_price || $open_price > $max_price){ return verify_err(null, '开盘价应在最低最高价之间'); }
        if($close_price < $min_price || $close_price > $max_price){ return verify_err(null, '收盘价应在最低最高价之间'); }
        if($now_price < $min_price || $now_price > $max_price){ return verify_err(null, '当前价应在最低最高价之间'); }
        $res = Exchangerate::where($_where)->update($data);
        return auto_return($res, '修改成功');
    }

    /*获取汇率记录列表（分页）*/
    public function rateList($data): array 
    {
        $res = Exchangerate::where('status','=',1)
                    ->orderBy('id', 'desc')
                    ->paginate($data['listRows'], null, null, $data['page'])
                    ->toArray();
        return auto_return_page($res, '已找到汇率记录列表数据', '没有汇率记录列表数据');
    }

    /*获取最新一条汇率记录*/
   /* public function oneNewRate(): array 
    {
        $_where['status'] = 1;
        $res = $this->model($this->exchangerateModel)->where($_where)->order('id desc')->find();
        return auto_return($res);
    }*/

    /*删除一条汇率记录*/
    public function delOneRate($data): array 
    {
        $res = Exchangerate::where([['status','=',1],['id','=',$data['id']]])->delete();
        return auto_return($res, '已删除该条记录');
    }


    

}